import { ref, toRefs } from "vue"

//导入map
import { useMapStore } from "@/stores/mapStore"
const { mapState } = toRefs(useMapStore())
const container = ref()
const content = ref()
export const useQueryEvent = () => {
  let service = { name: "traffic", layerId: 2 }
  var source = new ol.source.Vector({})
  var layer = new ol.layer.Vector({
    source,
    style: new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        /* 填充色 */
        fill: new ol.style.Fill({
          color: "rgba(255, 0, 0,.9)",
        }),
        /* 描边 */
        stroke: new ol.style.Stroke({
          color: "skyblue",
          width: 2,
        }),
      }),
    }),
  })

  function queryEvent() {
    mapState.value.map.addLayer(layer)
    // mapState.value.map.addOverlay(popup)
    Query.queryEventByGeom({
      service,
      /* 这样就能在函数外面拿到查询到的值 */
      callback: (res) => {
        var format = new Zondy.Format.PolygonJSON()
        /* 将mapgis要素json反序列化为ol.feature类型数组 */
        var features = format.read(res)
        /* 将查询到的要素添加到高亮图层中 */
        source.addFeatures(features)
      },
    })
  }

  /**
   * 为map添加点击事件监听，渲染弹出popup
   */
  // var position=ref([])
  setTimeout(() => {
    mapState.value.map.on("click", function (evt) {
      //判断当前单击处是否有要素，捕获到要素时弹出popup
      var feature = mapState.value.map.forEachFeatureAtPixel(
        evt.pixel,
        function (feature, layer) {
          return feature
        }
      )
      if (feature) {
        const msg = feature.values_.values_
        console.log(msg)
        content.value.innerHTML = `事件编号:${msg["事件编号"]}<br/>
        事件类型:${msg["事件类型"]}<br/>
        事件等级:${msg["事件等级"]}<br/>
        发生地点:${msg["发生地点"]}<br/>
        发生时间:${msg["发生时间"]}<br/>
        `
        const clientX = evt.pointerEvent.clientX - 50
        const clientY = evt.pointerEvent.clientY - 150
        container.value.style.top = clientY + "px"
        container.value.style.left = clientX + "px"
        console.log(evt.pointerEvent.clientY)
      }
    })
  })

  /**
   * 为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
   */
  setTimeout(() => {
    mapState.value.map.on("pointermove", function (e) {
      var pixel = mapState.value.map.getEventPixel(e.originalEvent)
      var hit = mapState.value.map.hasFeatureAtPixel(pixel)
      mapState.value.map.getTargetElement().style.cursor = hit ? "pointer" : ""
    })
  })
  //关闭事件查询函数
  function closeQueryEvent() {
    source.clear()
    mapState.value.map.removeLayer(layer)
    container.value.innerHTML = ""
    container.value.style.top = "-20px"
    container.value.style.left = "-70px"
  }

  return { queryEvent, container, content, closeQueryEvent }
}
